<template>
  <xr-create
    :loading="loading"
    :title="title"
    @close="hidenView"
    @save="saveField">
    <i
      slot="title-append"
      class="wk wk-icon-fill-help wk-help-tips"
      data-type="16"
      data-id="43" />
    <create-sections
      :title="$t('crm.marketing.8ba8f1fd7a35f25d204cff9dbef82acc')">
      <flexbox direction="column" align="stretch">
        <div class="crm-create-body">
          <wk-form
            ref="dataForm"
            :model="dataForm"
            :rules="dataRules"
            :field-from="dataForm"
            :field-list="fieldList"
            label-position="top"
            @change="formChange"
          >
            <template slot-scope="{}">
              <wk-user-dep-dialog-select
                style="width: 100%;"
                :user-value.sync="dataForm.relationUserId"
                :dep-value.sync="dataForm.relationDeptId"
                :sub-dept-contain.sync="dataForm.isNeedChild"
                :placeholder="$t('crm.marketing.22f2c2d1e41195850896559a05d4215a')"
                :props="{
                  showSubDeptContain: true,
                  showDisableUser: false
                }"
              />
            </template>
          </wk-form>
        </div>
      </flexbox>
      <el-checkbox v-model="onlyOne" class="only-check">
        {{ $t('crm.marketing.8eb3e3f0cfc54fc57685f21ddcf15041') }}
        <span style="color: #6b778c;">
          {{ $t('crm.marketing.9bc4295a69e7e99f61efce3b11147385') }}
        </span>
      </el-checkbox>
    </create-sections>
    <create-sections
      :title="$t('crm.marketing.ffb17aba94abeb8161feea7c654536c5')">
      <i
        slot="header"
        class="wk wk-icon-fill-help wk-help-tips"
        data-type="16"
        data-id="145" />
      <detail-img
        :detail="imageData"
        @change="detailImgChange"
        @delete="deleteImg" />
    </create-sections>
    <create-sections
      :title="$t('crm.marketing.0255286d64c53d3e8c623286aa4eb511')">
      <div class="field-set">
        <div class="field-set__name">
          {{ $t('crm.marketing.3f35358ba622b1fbbbf56426245d27f9') }}
        </div>
        <flexbox wrap="wrap">
          <el-checkbox
            v-for="(item, index) in fieldData"
            :key="index"
            v-model="item.isHidden"
            :true-label="0"
            :false-label="1">
            {{ item.name }}
          </el-checkbox>
        </flexbox>
      </div>
    </create-sections>
  </xr-create>
</template>

<script type="text/javascript">
import { filedGetFieldAPI } from '@/api/crm/common'
import {
  crmMarketingSaveAPI,
  crmMarketingUpdateAPI
} from '@/api/crm/marketing'
import {
  crmMarketingFormListAPI,
  crmMarketingFieldListAPI
} from '@/api/admin/crm'

import XrCreate from '@/components/XrCreate'
import CreateSections from '@/components/CreateSections'
import MarketingMixin from './Marketing'
import DetailImg from './DetailImg'
import WkForm from '@/components/NewCom/WkForm'
import WkUserDepDialogSelect from '@/components/NewCom/WkUserDepDialogSelect'

import { objDeepCopy, formatTimeToTimestamp } from '@/utils'

export default {
  name: 'MarketingCreate',
  components: {
    XrCreate,
    CreateSections,
    WkForm,
    DetailImg,
    WkUserDepDialogSelect
  },

  filters: {},

  mixins: [MarketingMixin],

  props: {
    /**
     * save:添加、update:编辑
     */
    action: {
      type: Object,
      default: () => {
        return {
          type: 'save',
          id: ''
        }
      }
    }
  },
  data() {
    const validateUserDept = (rule, value, callback) => {
      if (this.dataForm && ((this.dataForm.relationUserId && this.dataForm.relationUserId.length > 0) || (this.dataForm.relationDeptId && this.dataForm.relationDeptId.length > 0))) {
        callback()
      } else {
        callback(new Error(this.$t('crm.marketing.5ffb0f5295fd1fea41bbf465ace5602c')))
      }
    }

    var validateTime = (rule, value, callback) => {
      if (this.dataForm.startTime && this.dataForm.endTime) {
        if (
          formatTimeToTimestamp(this.dataForm.startTime) >=
          formatTimeToTimestamp(this.dataForm.endTime)
        ) {
          callback(new Error(this.$t('crm.marketing.7539956afbb671d13ebbcb795c55d6f2')))
        }
      }
      callback()
    }

    return {
      // 标题展示名称
      title: '',
      loading: false,
      fieldList: [], // 字段
      dataRules: {
        marketingName: {
          required: true,
          message: this.$t('crm.marketing.7d0f79673eefefbfdc02959941bf6490'),
          trigger: 'change'
        },
        crmType: {
          required: true,
          message: this.$t('crm.marketing.697228e7fe733d03de03ee171187d800'),
          trigger: 'change'
        },
        relationUserDeptId: {
          required: true,
          validator: validateUserDept,
          trigger: ['blur', 'change']
        },
        endTime: [{
          required: true,
          message: this.$t('crm.marketing.376e14423a1f18b602a32521b484bf2f'),
          trigger: 'change'
        },
        { validator: validateTime, trigger: 'blur' }],
        startTime: [{
          required: true,
          message: this.$t('crm.marketing.e070766bf375f59dec49f8e1936f5b3f'),
          trigger: 'change'
        },
        { validator: validateTime, trigger: 'blur' }],
        remark: {
          required: true,
          message: this.$t('crm.marketing.c53bdfc651336cb90f604fcbdaa0777b'),
          trigger: 'change'
        }
      }, // 字段规则
      dataForm: {
        marketingName: '',
        crmType: '2', // 2 客户 1 线索
        relationUserId: [],
        relationDeptId: [],
        marketingType: '',
        endTime: '',
        fieldDataId: '',
        browse: '',
        marketingMoney: '',
        submitNum: '',
        startTime: '',
        address: '',
        remark: '',
        isNeedChild: 0
      },
      // 只能填写一次
      onlyOne: true, // 0 不限制 1 只能填写一次
      // 图片信息
      imageData: {
        mainFile: [],
        detailFile: []
      },
      // 展示的数组
      fieldData: []
      // showFieldList: []
    }
  },

  computed: {},

  mounted() {
    // 获取title展示名称
    document.body.appendChild(this.$el)
    this.title = this.getTitle()

    this.getCustomFormList()
  },

  destroyed() {
    // remove DOM node after destroy
    if (this.$el && this.$el.parentNode) {
      this.$el.parentNode.removeChild(this.$el)
    }
  },

  methods: {
    /**
     * 获取字段信息
     */
    getFieldConfigIndex() {
      const request = this.dataForm.crmType > 2 ? crmMarketingFieldListAPI : filedGetFieldAPI
      const params = this.dataForm.crmType > 2 ? {
        id: this.dataForm.crmType
      } : {
        label: this.dataForm.crmType,
        type: '1' //  一维数组
      }
      request(params)
        .then(res => {
          const resData = (res.data || []).filter(item => ![
            'user',
            'structure',
            'file',
            'desc_text', // 不支持 描述文字、地址、定位、手写签名、图片、明细表格、分组标题 自定义编号 自定义标签 分组标题
            'position',
            'location',
            'handwriting_sign',
            'detail_table',
            'serial_number',
            'field_attention',
            'field_group',
            'pic',
            'customer' // 上级客户
          ].includes(item.formType))

          if (
            this.action.type == 'update' &&
            this.dataForm.crmType == this.action.detail.crmType
          ) {
            const showFieldsStr = this.action.detail.fieldDataId || ''

            const showFields = showFieldsStr.split(',')
            const fieldList = []
            for (let index = 0; index < resData.length; index++) {
              const element = resData[index]
              if (this.isShowField(element.formType)) {
                if (showFields.includes(element.fieldId)) {
                  element.isHidden = 0
                } else {
                  element.isHidden = 1
                }
                fieldList.push(element)
              }
            }
            this.fieldData = fieldList
          } else {
            const fieldList = []
            for (let index = 0; index < resData.length; index++) {
              const element = resData[index]
              if (this.isShowField(element.formType)) {
                element.isHidden = 0
                fieldList.push(element)
              }
            }
            this.fieldData = fieldList
          }
        })
        .catch(() => {})
    },

    /**
     * 获取自定义数组
     */
    getCustomFormList() {
      this.loading = true
      crmMarketingFormListAPI({
        page: this.currentPage,
        limit: this.pageSize,
        pageType: 0
      })
        .then(res => {
          const list = res.data || []
          const settingList = [
            { name: this.$t('crm.marketing.cbc2071554fd564088edd0216896e713'), value: '2' },
            { name: this.$t('crm.marketing.ae6ecfbca2dae8ed575153fd54e2c289'), value: '1' }
          ].concat(list.map(item => {
            return {
              name: item.title,
              value: item.id
            }
          }))
          this.fieldList = this.getFieldList(settingList)
          this.initInfo()
          this.loading = false
        })
        .catch(() => {
          this.loading = false
        })
    },

    /**
     * 初始化数据
     */
    initInfo() {
      if (this.action.type == 'update') {
        const dataForm = {}
        for (let index = 0; index < this.fieldList.length; index++) {
          const element = this.fieldList[index]
          if (element.field === 'relationUserDeptId') {
            dataForm.relationUserId = element.value.relationUserId
            dataForm.relationDeptId = element.value.relationDeptId
          } else {
            dataForm[element.field] = element.value
          }
        }

        this.dataForm = dataForm

        this.onlyOne = this.action.detail.second == 1

        this.imageData = {
          mainFile: this.action.detail.mainFileList || [],
          detailFile: this.action.detail.detailFileList || []
        }

        this.getFieldConfigIndex()
      } else {
        this.getFieldConfigIndex()
      }
    },

    /**
     * 获取字段数据
     */
    getFieldList(crmTypeSetting) {
      const detailData = this.action.type == 'update' ? this.action.detail : null
      const crmType = detailData ? detailData.crmType : '2'
      return [
        {
          field: 'marketingName',
          name: this.$t('crm.marketing.a4fed13f51d91c420025a5ed7eaf9dc3'),
          formType: 'text',
          inputTips: '',
          setting: [],
          value: detailData ? detailData.marketingName : '',
          width: '',
          tipType: 'system-help',
          helpType: '16',
          helpId: '48'
        },
        {
          field: 'crmType',
          name: this.$t('crm.marketing.826ddd4b15479f0e0cae11c4063d20bd'),
          formType: 'select',
          inputTips: this.$t('crm.marketing.980f8498b3c948cf92a6e89bd7dd640d'),
          setting: crmTypeSetting,
          disabled: this.action.type == 'update',
          value: crmType.toString(),
          width: '',
          tipType: 'system-help',
          helpType: '16',
          helpId: '141'
        },
        {
          field: 'relationUserDeptId',
          name: this.$t('crm.marketing.a1dc391ad0b7df6c3e5a46906a6e3148'),
          formType: 'userDep',
          radio: false,
          inputTips: this.$t('crm.marketing.3f13d7ac0a153ef5c191169d2be124b3'),
          setting: [],
          value: detailData ? {
            relationUserId: (detailData.relationUserInfo || []).map(item => item.userId),
            relationDeptId: (detailData.relationDeptInfo || []).map(item => item.id || item.deptId)
          } : {
            relationUserId: [],
            relationDeptId: []
          },
          width: '',
          tipType: 'system-help',
          helpType: '16',
          helpId: '142'
        },
        {
          field: 'marketingType',
          name: this.$t('crm.marketing.92986d3bd3d3b8d881d42cc4df158b9e'),
          formType: 'select',
          inputTips: '',
          setting: [
            this.$t('crm.marketing.e8e9ff16e81281f66073a4e3e65170f2'),
            this.$t('crm.marketing.1427d8c391332c33104cb11e1f54fc32'),
            this.$t('crm.marketing.bba272e314b6c2dcd47b2b93be2dd386'),
            this.$t('crm.marketing.0510272e6fddba82dfb4e5476e46f346'),
            this.$t('crm.marketing.98e5e10aa085fef40356c2c46ed94bd6'),
            this.$t('crm.marketing.1c6884df755a44d8b64633c17e787a7d')
          ],
          value: detailData ? detailData.marketingType : '',
          width: ''
        },
        {
          field: 'startTime',
          name: this.$t('crm.marketing.485cee332327477b9840a7e08569d4fe'),
          formType: 'datetime',
          inputTips: '',
          setting: [],
          value: detailData ? detailData.startTime : '',
          width: '',
          tipType: 'system-help',
          helpType: '16',
          helpId: '143'
        },
        {
          field: 'endTime',
          name: this.$t('crm.marketing.a2d1424ab55660d1e90203e51bce8c9b'),
          formType: 'datetime',
          inputTips: '',
          setting: [],
          value: detailData ? detailData.endTime : '',
          width: '',
          tipType: 'system-help',
          helpType: '16',
          helpId: '143'
        },
        {
          field: 'browse',
          name: this.$t('crm.marketing.5825b962182e72c41af650adc3a68d3a'),
          formType: 'number',
          inputTips: '',
          setting: [],
          value: detailData ? detailData.browse || '' : '',
          width: '',
          tipType: 'system-help',
          helpType: '16',
          helpId: '144'
        },
        {
          field: 'submitNum',
          name: this.$t('crm.marketing.045e42b303ed797d06465f8564038ad4'),
          formType: 'number',
          inputTips: '',
          setting: [],
          value: detailData ? detailData.submitNum || '' : '',
          width: '',
          tipType: 'system-help',
          helpType: '16',
          helpId: '144'
        },
        {
          field: 'marketingMoney',
          name: this.$t('crm.marketing.f742e3a375559b4e8ec7641500c8a45d'),
          formType: 'floatnumber',
          inputTips: '',
          setting: [],
          value: detailData ? detailData.marketingMoney : '',
          width: ''
        },
        {
          field: 'address',
          name: this.$t('crm.marketing.99f43ae59605af91d385f108edaba290'),
          formType: 'text',
          inputTips: '',
          setting: [],
          value: detailData ? detailData.address : '',
          width: ''
        },
        {
          field: 'synopsis',
          name: this.$t('crm.marketing.dea4707a2a9b0eb05f6441cbc14c0e6f'),
          formType: 'textarea',
          inputTips: '',
          setting: [],
          value: detailData ? detailData.synopsis : '',
          width: ''
        }
      ]
    },

    /**
     * 字段的值更新
     */
    formChange(item) {
      if (item.field == 'crmType') {
        this.getFieldConfigIndex()
      }
    },

    /**
     * 修改图片
     */
    detailImgChange(type, data) {
      if (type === 'mainFile') {
        this.imageData.mainFile = data
      } else if (type === 'detailFile') {
        this.imageData.detailFile = data
      }
    },

    deleteImg(type, data) {
      if (type === 'mainFile') {
        this.imageData.mainFile = data
      } else if (type === 'detailFile') {
        this.imageData.detailFile = data
      }
    },

    /**
   * 保存数据
   */
    saveField() {
      this.$refs.dataForm.instance.validate(valid => {
        if (valid) {
          const params = objDeepCopy(this.dataForm)
          params.second = this.onlyOne ? 1 : 0 // 0 不限制 1 只能填写一次

          let fieldDataId = ''
          this.fieldData.forEach((item, index) => {
            if (item.isHidden == 0) {
              fieldDataId += `,${item.fieldId}`
            }
          })
          params.fieldDataId = fieldDataId ? fieldDataId + ',' : ''
          params.relationUserId = ',' + this.dataForm.relationUserId.join(',') + ','
          params.relationDeptId = ',' + this.dataForm.relationDeptId.join(',') + ','
          params.browse = params.browse ? params.browse : 0
          params.submitNum = params.submitNum ? params.submitNum : 0
          // params.endTime = params.endTime
          // params.startTime = params.startTime

          // 活动图片
          params.mainFileIds = this.imageData.mainFile ? this.imageData.mainFile.map(item => item.fileId).join(',') : ''
          params.detailFileIds = this.imageData.detailFile ? this.imageData.detailFile.map(item => item.fileId).join(',') : ''
          this.submiteParams(params)
        } else {
          this.getFormErrorMessage(this.$refs.dataForm.instance)
          return false
        }
      })
    },

    /**
     * 获取error错误
     */
    getFormErrorMessage(crmForm) {
      // 提示第一个error
      if (crmForm.fields) {
        for (
          let index = 0;
          index < crmForm.fields.length;
          index++
        ) {
          const ruleField = crmForm.fields[index]
          if (ruleField.validateState == 'error') {
            this.$message.error(ruleField.validateMessage)
            break
          }
        }
      }
    },

    /**
     * 上传
     */
    submiteParams(params) {
      this.loading = true
      let request = crmMarketingSaveAPI
      if (this.action.type == 'update') {
        request = crmMarketingUpdateAPI
        params.marketingId = this.action.id
      }

      request(params)
        .then(res => {
          this.loading = false
          this.hidenView()
          this.$message.success(this.action.type == 'update' ? this.$t('crm.marketing.ddd7996a2d2787992a060b0e22498fb1') : this.$t('crm.marketing.a8f8a9ccbe85205291626cdce6846db9'))
          // 回到保存成功
          this.$emit('save-success')
        })
        .catch(() => {
          this.loading = false
        })
    },

    hidenView() {
      this.$emit('hiden-view')
    },

    /**
     * 根据类型获取标题展示名称
     */
    getTitle() {
      return this.action.type == 'update' ? this.$t('crm.marketing.72f1a6356d93194b2d08a7279dfe17ab') : this.$t('crm.marketing.3b2c489fbad75f3830596b4bf7d5307d')
    }
  }
}
</script>

<style lang="scss" scoped>
.crm-create-body {
  flex: 1;
  overflow-x: hidden;
  overflow-y: auto;

  ::v-deep.el-form {
    padding-bottom: 10px;
  }
}

.handle-bar {
  position: relative;

  .handle-button {
    float: right;
    margin-top: 5px;
    margin-right: 20px;
  }
}

.wk-user-dep-select {
  width: 100%;
}

// 是否能选择
.only-check {
  padding: 0 10px 10px;
}

// 字段调整
.field-container {
  width: 90%;
  padding: 10px 10px 40px;
}

// 字段设置
.field-set {
  padding: 15px;
  margin: 10px 20px 40px;
  font-size: 13px;
  border: 1px solid $--border-color-base;
  border-radius: $--border-radius-base;

  &__name {
    margin-bottom: 10px;
    color: $--color-text-secondary;
  }

  .el-checkbox {
    flex: 0 0 30%;
    margin-right: 8px;
    margin-bottom: 8px;
  }
}
</style>
